# GPL3 or later

from http.server import BaseHTTPRequestHandler, HTTPServer
from subprocess import *
import urllib.parse
import json
import os
import time
import commands
import local_markdown as markdown
import datetime

from ui import *

ADDRESS = "/"
PORT = 8080
CSS = "http://192.168.0.101:8080/css"

class handler(BaseHTTPRequestHandler):

    def start_page(self):
        self.send_response(200)
        if "/json/" in self.path:
            self.send_header('Content-type', 'application/json')
        elif self.path == "/css":
            self.send_header('Content-type', 'text/css')
        elif self.path == "/ttf":
            self.send_header('Content-type', 'font/ttf')
        elif self.path in ["/favicon.png", "/logo"]:
            self.send_header('Content-type', 'image/png')
        else:
            self.send_header('Content-type', 'text/html')
        self.end_headers()

    def send(self, textin):

        software = self.path.replace("/", "").replace("+", " ")
        
        if software:
            software = ": "+software[0].upper()+software[1:].lower()

        
        textin = str(textin)
        cssfile = open("default.css")
        cssfile = cssfile.read()
        csstext = "<style>"+cssfile+"</style>"
        text = """<meta charset="Utf-8">
        <!-- Welcome to Free Competitors Page Source!!!-->

        """
        text = text + "<!-- Let's add some CSS, you can edit 'config.json' to change it. -->\n"
        text = text + '<head>'+csstext+'\n\n'
        text = text + "<!-- Now we want the favicon to be PNG instead of ICO -->\n\n"
        text = text + '<link rel="icon" href="https://em-content.zobj.net/thumbs/120/mozilla/36/guitar_1f3b8.png">\n\n'
        text = text + "<!-- Now the title -->\n\n"
        text = text + '<title>Music Remote Control</title></head>\n\n'
        text = text + "<!-- Now the body. The main part of the page, so to speak. -->\n"
        text = text + '<body>\n\n'+textin+'\n\n</body>'
        

        
        self.start_page()
        self.wfile.write(text.encode("utf-8"))
        
    def do_GET(self):
        
        
        
        if self.path == "/css":

            # The css file

            cssfile = open("default.css", "rb")
            cssfile = cssfile.read()
            self.wfile.write(cssfile)
        elif self.path == "/favicon.png":

            # The css file

            self.wfile.write(b"")

        elif self.path.startswith("/now_playing"):

            page = """
            <meta http-equiv="refresh" content="3">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, 
user-scalable=no">
            """
            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)

            parsed = urllib.parse.urlparse(self.path)
            parsed = urllib.parse.parse_qs(parsed.query)
            
            username = parsed.get("user_name", [""])[0]
            password = parsed.get("password", [""])[0]
            if stuff.get("users", {}).get(username, {}).get("password", "") != password:
                password = ""
            
            
            

            videoId = stuff.get("now_playing")
            data = stuff.get("songs", {}).get(videoId, {})
                
            
            # Percent of the song ( Progress bar in the bottom
            duration = stuff.get("songs", {}).get(videoId, {}).get("duration", 1)
            started = stuff.get("last_played", 0)
            percent = str(max(0, min(1, (time.time()-started) / duration)) * 100)

            page = page + "<ul><li>"
            

            
            page = page +user_emoji(stuff.get("now_username", ""), stuff)
            page = page + " | "+data.get("title", "")+"<br>"
            page = page + "<i>"+timestring(duration)+" / "+timestring(int(time.time()-started))+"</i> "

            if password and username != stuff.get("now_username", ""):
                page = page +' </li><li><a class="button" href="/?user_name='+username+'&password='+password+'&item='+"https://yewtu.be/"+videoId+'">+</a>'

            elif password:
                page = page +' </li><li><a class="button" href="/?user_name='+username+'&password='+password+'&item=skip">⏭</a>'

                
            
            page = page + """
            </li></ul><br><br><br><br>
            <div class="back_progress">
            <div class="front_progress" style="width:"""+str(percent)+"""%">  
            </div>
            </div>"""
            

            self.send(page)
            

        else:

            
            
            parsed = urllib.parse.urlparse(self.path)
            parsed = urllib.parse.parse_qs(parsed.query)

            username = parsed.get("user_name", [""])[0]
            password = parsed.get("password", [""])[0]
            command = parsed.get("item", [""])[0]
            volume = parsed.get("volume", [""])[0]
            

            page = "<div class=\"side_found\"><code>"+username+"</code><br><br>"
            page = page + """<meta name="viewport" content="width=device-width, initial-scale=1.0, 
user-scalable=no">"""
            page = page + "<code>"+command+"</code><br><br>"

            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)

            new_date_format = "%Y/%m/%d"
            today = datetime.datetime.strftime(datetime.datetime.today(), new_date_format)
            for d in range(400):
                yesterday = datetime.datetime.strftime(datetime.datetime.today()-datetime.timedelta(days=d+1), new_date_format)
                if yesterday in stuff.get("volume", {}):
                    break
            
            if volume:
                page = """<meta http-equiv="refresh" content="0; url=/?user_name="""+username+"""&password="""+password+"""&item="""+volume+"""%" />"""

            if not stuff.get("users", {}).get(username, {}).get("password", "") and password:
                try:
                    stuff["users"][username]["password"] = password
                    with open('stuff.json', 'w') as fp:
                        json.dump(stuff, fp, indent=4)

                except Exception as e:
                    print( "ERROR", e)
                    
            if username not in stuff.get("users", {}):
                page = page + "<i>To create an account use either the Matrix group, or ask the administrator to create an acount for you manually.<br><br>"
                    
            elif stuff.get("users", {}).get(username, {}).get("password", "") == password:
            
                answer = commands.execute(username, command, password=password)
                afterpage = ""
                if not answer and command:

                    page = page + '<details class="button"><summary>🎸 From Your History בהיסטוריה שלך</summary><br>'
                    answer = commands.execute(username, "history "+command, password=password)
                    page = page + markdown.convert(answer, isfile=False) + "<br><br>"

                    page = page + '</details><br><details class="button"><summary>🎶 In All Songs בכל השירים</summary><br>'
                    answer = commands.execute(username, "songs "+command, password=password)
                    page = page + markdown.convert(answer, isfile=False) + "<br><br>"

                    page = page + '</details><br><details class="button"><summary>🌐 From YouTube ביוטיוב</summary><br>'
                    answer = commands.execute(username, "search "+command, password=password)
                    afterpage = "</details>"
                elif not answer:
                    answer = commands.execute(username, "help", password=password)
                page = page + markdown.convert(answer, isfile=False) + "<br><br>"+afterpage

            
            else:
                page = page + "Invalid Password<br><br>"

            if not username or not password:
                page = page + """
                </div>
                <div class="searchbar">           	
                <center>
                <br><br>

                <form action="/" method="GET">
                <input id="user_name" name="user_name" autofocus required placeholder="Matrix Username" size="8"><br>
                <input id="password" name="password" type="password"  placeholder="Password" size="8" /><br>
                <input name="item" type="hidden" value='help'>
                <button type="submit">Login</button>
                </form>
                </center></div>

                """
            else:

                
                volume_was = stuff.get("volume", {}).get(today, {}).get("users", {}).get(username, stuff.get("volume", {}).get(yesterday, {}).get("average", 20))
                if command.endswith("%"):
                    volume_was = command.replace("%", "")
                
                
                page = page + """
                <br><br><br><br><br><br><br><br><br><br><br><br>
                </div>
                <div class="searchbar">           	
                <center>

                <form action="/" method="GET">
                <a class="button" href="/?user_name="""+username+"""&password="""+password+"""">🏠️</a>
                <input id="user_name" name="user_name" type="hidden" value='"""+username+"""'>
                <input id="password" name="password" type="hidden" value='"""+password+"""'>
                <input type="text" name="item" class="search" placeholder="Command" >
                <button type="submit">▶</button>
                </form>
                <br>
                
                <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=list">⬆</a>
                <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=history">🎸</a>
                
                <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=set_volume">🔈</a>

                <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=songs">🎶</a>
                

                </center></div>

                <div class="nowplayingbar"><iframe src="/now_playing?user_name="""+username+"""&password="""+password+"""" title="now playing" width="100%" height="200" style="border:none;" ></iframe></div>

                """
                   

            self.send(page)


serve = HTTPServer(("", PORT), handler)
print("Now serving on port "+ str(PORT) +" at "+ ADDRESS +".")
serve.serve_forever()
